const e = require("express");
const express = require("express");
const pool = require("../pool.js");
const router = express.Router();

//加载
router.get("/shopcart", (req, res, next) => {
  // console.log(req.query);
  pool.query(
    "select * from shopcart where uid=?",
    req.query.uid,
    (err, result) => {
      if (err) {
        next(err);
        return;
      } else {
        if (result.length) {
          res.send({ code: 200, data: result });
        } else {
          res.send({ code: 201, msg: "加载错误" });
        }
      }
    }
  );
});
router.get("/details", (req, res, next) => {
  pool.query(
    "select * from details where pid=?",
    req.query.pid,
    (err, result) => {
      if (err) {
        next(err);
        return;
      } else {
        if (result.length) {
          res.send({ code: 200, data: result });
        } else {
          res.send({ code: 201, msg: "查询失败" });
        }
      }
    }
  );
});
router.post("/addshop", (req, res, next) => {
  req.body.uid=Number(req.body.uid)
  req.body.count=Number(req.body.count)
  if(!req.body.uid){
    res.send({code:201,msg:'添加失败,请登录'})
    return
  }else{
    pool.query('select * from shopcart where products=?',req.body.products,(err,result)=>{
      if(err){
        next(err)
        return
      }else{
        if(result.length){
          let count=result[0].count+req.body.count
          pool.query('update shopcart set count=? where products=?',[count,req.body.products],(err,resul)=>{
            if(err){
              next(err)
              return
            }else{
              if(resul.affectedRows){
                res.send({code:200,msg:'添加成功'})
              }else{
                res.send({code:201,msg:'添加失败'})
              }
            }
          })
        }else{
          pool.query('insert into shopcart set ?',req.body,(err,resok)=>{
            if(err){
              next(err)
              return
            }else{
              if(resok.affectedRows){
                res.send({code:200,msg:'添加成功'})
              }else{
                res.send({code:201,msg:'添加失败'})
              }
            }
          })
        }
      }
    })
  }
});
router.get('/delshop',(req,res,next)=>{
  pool.query('delete from shopcart where sid=?',req.query.sid,(err,result)=>{
    if(err){
      next(err)
      return
    }else{
      // console.log(result);
      if(result.affectedRows){
        res.send({code:200,msg:'删除成功'})
      }else{
        res.send({code:201,msg:'删除失败'})
      }
    }
  })
})
module.exports = router;
